package chu.dejian.restApi;

import chu.dejian.conf.BLEPreference;
import com.sam.utils.L;
import retrofit.RequestInterceptor;
import retrofit.RestAdapter;

/**
 * Created by chuchuyajun on 03/09/2015.
 */
public class RestClient {
    private static RestClient client,loginedClient;
    private static String token;
    private static final String BASE_URL = "https://api.dejianwang.com/v1";
    private RestApiService apiService;

    public static synchronized RestClient getUnAuthedClient(){
        if(client == null) client = new RestClient();
        return client;
    }

    public static synchronized RestClient getAuthedClient(){
        if(token == null) throw new NullPointerException("token为空，请在登录成功后设置token");
        if(loginedClient == null) loginedClient = new RestClient(token);
        return loginedClient;
    }

    public String getToken(){
        return token;
    }
    public void clearToken(){
        token = null;
        BLEPreference.getInstance().setToken(null);
    }
    public void setToken(String token){
        RestClient.token = token;
        loginedClient = new RestClient(token);
        BLEPreference.getInstance().setToken(token);
    }
    /**
     * 请求头不带token验证信息的请求客户端
     */
    public RestClient()
    {
        RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint(BASE_URL)
                .setLogLevel(RestAdapter.LogLevel.FULL)
                .build();
        apiService = restAdapter.create(RestApiService.class);
        setToken(BLEPreference.getInstance().getToken(null));
    }

    /**
     * 请求头带token验证信息的请求客户端
     */
    public RestClient(final String userToken)
    {
        RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint(BASE_URL)
                .setRequestInterceptor(new RequestInterceptor() {
                    @Override
                    public void intercept(RequestFacade requestFacade) {
                        requestFacade.addHeader("Authorization", "token " + userToken);
                    }
                }).setLogLevel(RestAdapter.LogLevel.FULL)
                .setLog(new RestAdapter.Log() {
                    @Override
                    public void log(String message) {
                        L.i(message);// code for storing logs in file
                    }
                }).build();

        apiService = restAdapter.create(RestApiService.class);
        RestClient.token = userToken;
    }

    public RestApiService getApiService(){
        return apiService;
    }



}
